﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using DbSharp.Framework.Storage.IO;

namespace DbSharp.Framework.Storage.Export
{
    public class ExcelExportWriter : IExportWriter
    {
        private void Prepare(string xlsFile, out bool isExcel2007)
        {
            if (File.Exists(xlsFile))
                File.Delete(xlsFile);

            string fileExt = Path.GetExtension(xlsFile);
            isExcel2007 = string.Equals(fileExt, ".xlsx", StringComparison.OrdinalIgnoreCase);
        }

        private void ExportScalar(string xlsFile, XElement dataRootElement)
        {
            bool isExcel2007;
            Prepare(xlsFile, out isExcel2007);

            var fileWriter = new ExcelFileWriter(xlsFile, isExcel2007);
            fileWriter.SaveToFile(dataRootElement);
        }

        private void ExportRecordset(string xlsFile, string excelSheetTitle, IEnumerable<XElement> listRecordElement, long exportRecordCount)
        {
            bool isExcel2007;
            Prepare(xlsFile, out isExcel2007);

            var fileWriter = new ExcelFileWriter(xlsFile, isExcel2007);

            List<string> listRowsGroupName = new List<string>();
            List<IEnumerable<XElement>> listRowsGroup = new List<IEnumerable<XElement>>();
            List<long> listExportRecordCount = new List<long>();

            listRowsGroupName.Add(string.Empty);
            listRowsGroup.Add(listRecordElement);
            listExportRecordCount.Add(exportRecordCount);

            string groupColumnHeader = string.Empty;
            var fieldColumnHeaders = fileWriter.GetFieldColumnHeaders(listRecordElement);

            fileWriter.SaveToFile(excelSheetTitle, groupColumnHeader, fieldColumnHeaders, listRowsGroupName, listRowsGroup, listExportRecordCount);
        }

     

        #region IExportWriter Members

        public void Export(string fileName, object obj, long exportRecordCount)
        {
            string excelSheetTitle = ExcelFileWriterHelper.GetSheetDefaultTitle();
            if (ExportWriterHelper.IsRecordset(obj))
            {
                ExportRecordset(fileName, excelSheetTitle, (IEnumerable<XElement>)obj, exportRecordCount);
            }
            else
            {
                ExportScalar(fileName, (XElement)obj);
            }
        }

        #endregion


    }
    
}
